/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ee.ut.math.esi.service;

import com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLEncoder;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;

/**
 *
 * @author ool
 */
public class AlchemyApiResource {

    private static final String BASE_URL = "http://access.alchemyapi.com/calls/text/TextGetRankedNamedEntities";
    private static final String API_KEY = "581a415ca69d07bb891a5a5e1ca116859bfe1f71";

    public Node searchEntities(String text) throws ParserConfigurationException, SAXException, IOException {
        String data = "apikey=" + API_KEY + "&text=" + URLEncoder.encode(text, "UTF-8");
        PostWebPageFetcher fetcher = new PostWebPageFetcher(new URL(BASE_URL), data);

        String xml = fetcher.getPageContent();
        
        DocumentBuilderFactory dbf = new DocumentBuilderFactoryImpl();
        DocumentBuilder db = dbf.newDocumentBuilder();
        ByteArrayInputStream input = new ByteArrayInputStream(xml.getBytes());
        Document doc = db.parse(input);

        return doc.getDocumentElement();
    }
}
